﻿using MediatR;
using Microsoft.AspNetCore.Server.HttpSys;
using SmartMedicalCare.API.Read.Applications.Commands;
using SmartMedicalCare.Domain;
using SmartMedicalCare.ErronCode;
using SmartMedicalCare.Infrastructure.Implaction;

namespace SmartMedicalCare.API.Read.Applications.CommandHandlers
{
    public class QueryHospitalCommandHandler : IRequestHandler<QueryHospitalCommand, APIResult<APIPaging<HospitalModel>>>
    {
        private readonly IBaseRespository<HospitalModel> hospRep;

        public QueryHospitalCommandHandler(IBaseRespository<HospitalModel> hospRep)
        {
            this.hospRep = hospRep;
        }

        public Task<APIResult<APIPaging<HospitalModel>>> Handle(QueryHospitalCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<HospitalModel>> result=new APIResult<APIPaging<HospitalModel>>();
            result.code = ResultCode.显示成功;
            result.Message= ResultCode.显示成功.ToString();

            var res = hospRep.GetAll().Where(x => !x.IsDeleted);

            if (!string.IsNullOrEmpty(request.Name))
            {
                res=res.Where(x=>x.Name.Contains(request.Name));
            }
            if (request.HospitalAddTow != null)
            {
                res=res.Where(x=>x.HospitalAddTow==request.HospitalAddTow);
            }
            //总条数
            var totalcount=res.Count();
            //总页数
            var totalpage=(int)Math.Ceiling(totalcount*1.0/request.Pagsize);
            //排序
            res = res.OrderByDescending(x => x.HospitalId).Skip((request.Pagindex - 1) * request.Pagsize).Take(request.Pagsize);

            APIPaging<HospitalModel> paging = new APIPaging<HospitalModel>();
            paging.totalCount = totalcount;
            paging.totalPage = totalpage;
            paging.Fdata=res.ToList();
            result.Data= paging;

            return Task.FromResult(result);
        }
    }
}
